
package com.heimali.happyreader.core.manager;

import com.heimali.happyreader.core.intf.IStoppable;
import com.heimali.happyreader.utils.Utils;

public class GlobalManager implements IStoppable {

    public static String TAG = "GlobalManager";
    private static GlobalManager sInstance;

    public ArticleManager articleManager;
    public UserManager userManager;

    private boolean mIsStopped = false;

    private final IStoppable[] getStoppable() {
        return Utils.asArray(articleManager, userManager);
    }

    public final static synchronized GlobalManager getInstance() {
        if (sInstance == null) {
            sInstance = new GlobalManager();
        }
        return sInstance;
    }

    private GlobalManager() {
        articleManager = new ArticleManager();
        userManager = new UserManager();
    }

    @Override
    public void stopNow() {
        mIsStopped = true;
        for (IStoppable stoppable : getStoppable()) {
            try {
                if (stoppable != null) {
                    stoppable.stopNow();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean isStopped() {
        return mIsStopped;
    }

    @Override
    public void destroyNow() {
        for (IStoppable stoppable : getStoppable()) {
            try {
                if (stoppable != null) {
                    if (isStopped())
                        stoppable.destroyNow();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

        sInstance = null;
    }

}
